﻿using System;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace NETXPF.Library
{
    /// <summary>
    /// This dictionary class is XML-serializable and binary-serializable. Cool, huh?
    /// </summary>
    [Serializable]
    [XmlRoot("dictionary")]
    public class SerializableDictionary : Dictionary<string, object>, IXmlSerializable
    {
        public SerializableDictionary()
            : base()
        {
        }

        public SerializableDictionary(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        #region IXmlSerializable Members

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(string));
            bool wasEmpty = reader.IsEmptyElement;
            reader.Read();
            if (wasEmpty)
                return;
            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
                reader.ReadStartElement("item");
                reader.ReadStartElement("key");
                string key = (string)keySerializer.Deserialize(reader);
                reader.ReadEndElement();
                reader.ReadStartElement("type");
                string type = (string)keySerializer.Deserialize(reader);
                reader.ReadEndElement();
                XmlSerializer valueSerializer = new XmlSerializer(Type.GetType(type));
                reader.ReadStartElement("value");
                object value = (object)valueSerializer.Deserialize(reader);
                reader.ReadEndElement();
                this.Add(key, value);
                reader.ReadEndElement();
                reader.MoveToContent();
            }
            reader.ReadEndElement();
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(string));
            foreach (string key in this.Keys)
            {
                writer.WriteStartElement("item");
                writer.WriteStartElement("key");
                keySerializer.Serialize(writer, key);
                writer.WriteEndElement();
                writer.WriteStartElement("type");
                keySerializer.Serialize(writer, this[key].GetType().FullName);
                writer.WriteEndElement();
                XmlSerializer valueSerializer = new XmlSerializer(this[key].GetType());
                writer.WriteStartElement("value");
                object value = this[key];
                valueSerializer.Serialize(writer, value);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }

        #endregion
    }
}
